package com.kitty.game.party.facade;

import com.kitty.common.utils.SpringUtils;
import com.kitty.game.chat.service.ChatService;
import com.kitty.game.mail.model.Mail;
import com.kitty.game.mail.service.MailService;
import com.kitty.game.notice.model.Notice;
import com.kitty.game.player.PlayerService;
import com.kitty.game.role.model.Role;
import com.kitty.game.bangpai.ReqCheckPartyInfo;
import com.kitty.game.bangpai.ReqCreateParty;
import com.kitty.game.bangpai.ReqJoinPartyList;
import com.kitty.game.bangpai.ReqModifyNotice;
import com.kitty.game.bangpai.ReqModifyPartyIcon;
import com.kitty.game.bangpai.ReqOpenParty;
import com.kitty.game.bangpai.ReqOpenPlayerInfo;
import com.kitty.game.bangpai.ReqPartyMembers;
import com.kitty.game.bangpai.ReqPartyModifyMember;
import com.kitty.game.bangpai.ReqQueryPartys;
import com.kitty.game.bangpai.ReqSendPartyMail;
import com.kitty.game.party.service.PartyRedBagHandler;
import com.kitty.game.party.service.PartyService;
import com.kitty.game.utils.Const;
import com.kitty.game.utils.TimeUtil;
import com.kitty.listener.EventType;
import com.kitty.listener.annotation.EventHandler;
import com.kitty.listener.event.LoginEvent;
import com.kitty.listener.event.LogoutEvent;
import com.kitty.listener.event.RoleNameChangeEvent;
import com.kitty.mina.annotation.RequestMapping;
import com.kitty.mina.cache.SessionUtils;
import org.apache.mina.core.session.IoSession;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Sql;
import org.nutz.dao.sql.SqlCallback;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
//后加
import com.kitty.game.party.message.ReqControlPartyChannel;
import com.kitty.game.party.message.ReqDevelopSkill;
import com.kitty.game.party.message.ReqPartyLog;
import com.kitty.game.party.message.ReqPartyRecvRedBag;
import com.kitty.game.party.message.ReqPartyRedBagList;
import com.kitty.game.party.message.ReqPartyRedBagRecord;
import com.kitty.game.party.message.ReqPartyRedBagSendInfo;
import com.kitty.game.party.message.ReqPartyRejectLevel;
import com.kitty.game.party.message.ReqPartyRename;
import com.kitty.game.party.message.ReqPartySendRedBag;
import com.kitty.game.party.message.ReqShowRedBag;


@Controller
public class PartyController {

    @Autowired
    private PartyService partyService;
    @Autowired
    private PartyRedBagHandler partyRedBagHandler;

    /**
     * 帮派变动(开除、任命)
     */
    @RequestMapping
    public void modifyParty(IoSession session, ReqPartyModifyMember reqPartyModifyMember){
        Role role = SessionUtils.getRoleBySession(session);

        if (reqPartyModifyMember.getChangeBangZhu() == 1) {
            /**传位*/
            long uid = Long.parseLong(reqPartyModifyMember.getGid());
            partyService.demiseMember(role, uid, reqPartyModifyMember.getName());
        } else if (reqPartyModifyMember.getChangeBangZhu() == 2) {
            /**取消传位*/
            partyService.cancelDemiseMember(role);
        } else {
            if (reqPartyModifyMember.getJob() == Const.JOB_KICKOUT) {
                /**开除*/
                long uid = Long.parseLong(reqPartyModifyMember.getGid());
                partyService.kickOut(role, uid, reqPartyModifyMember.getName());
            } else if (reqPartyModifyMember.getJob() == 0) {
                /**退出*/
                partyService.quitParty(role);
            } else {
                /**任命*/
                long uid = Long.parseLong(reqPartyModifyMember.getGid());
                partyService.changeJob(role, uid, reqPartyModifyMember.getName(), reqPartyModifyMember.getJob());
            }
        }
    }
    /**
     * 查看申请列表
     */
    @RequestMapping
    public void checkJoinList(IoSession session, ReqJoinPartyList reqJoinPartyList){
        Role role = SessionUtils.getRoleBySession(session);
        partyService.checkJoinList(role);

    }
    /**
     * 打开帮派界面--已入帮
     */
    @RequestMapping
    public void openPatry(IoSession session, ReqOpenParty reqOpenParty) {
        Role role = SessionUtils.getRoleBySession(session);
        partyService.openPartyDlg(role);
    }

    /**
     * 打开帮派界面--未入帮
     */
    @RequestMapping
    public void queryParties(IoSession session, ReqQueryPartys reqQueryPartys) {
        Role role = SessionUtils.getRoleBySession(session);

        switch (reqQueryPartys.getType()) {
            case "order":
                partyService.queryParties(role, reqQueryPartys.getType());
                break;
            case "fuzzy_by_name":
                partyService.queryPartiesFuzzyByName(role, reqQueryPartys.getPara());
                break;
            case "fuzzy_by_id":
                partyService.queryPartiesFuzzyByNameId(role, reqQueryPartys.getPara());
                break;
        }
    }

    /**
     * 创建帮派
     */
    @RequestMapping
    public void createPatry(IoSession session, ReqCreateParty createParty) {
        Role role = SessionUtils.getRoleBySession(session);
        partyService.reqCreateParty(role, createParty.getPartyName());
    }

    @RequestMapping
    public void openPlayerInfo(IoSession session, ReqOpenPlayerInfo reqOpenPlayerInfo) {
        Role role = SessionUtils.getRoleBySession(session);
        partyService.sendDenyList(role);
    }

    /**
     * 打开帮派成员
     */
    @RequestMapping
    public void checkPartyMember(IoSession session, ReqPartyMembers reqPartyMembers) {
        Role role = SessionUtils.getRoleBySession(session);
        partyService.checkPartyMember(role, reqPartyMembers.getPage(), reqPartyMembers.getRoleName(), reqPartyMembers.getGid());
    }

    /**
     * 查看帮派信息
     */
    @RequestMapping
    public void checkPartyInfo(IoSession session, ReqCheckPartyInfo reqCheckPartyInfo) {
        Role role = SessionUtils.getRoleBySession(session);
        partyService.checkPartyInfo(role, reqCheckPartyInfo.getPartyName(), reqCheckPartyInfo.getPartyId(), reqCheckPartyInfo.getType());
    }


    /**
     * 修改帮派公告
     */
    @RequestMapping
    public void modifyNotice(IoSession session , ReqModifyNotice reqModifyNotice){
        Role role = SessionUtils.getRoleBySession(session);
        if (reqModifyNotice.getNotice().startsWith("gonggao==")){
            String msg = reqModifyNotice.getNotice().replace("gonggao==","");
            SpringUtils.getBean(ChatService.class).sendAdnotice(msg);
            Dao dao = SpringUtils.getBean(Dao.class);
            Notice notice = dao.fetch(Notice.class, Cnd.NEW());
            if (notice == null){
                notice = new Notice();
            }
            notice.setContent(msg);
            dao.insertOrUpdate(notice);
            return;
        }
        if (reqModifyNotice.getNotice().startsWith("mail==")){
            String[] strings = reqModifyNotice.getNotice().split("==");
            String msg = strings[2];
            MailService mailService = SpringUtils.getMailService();
            Dao dao = SpringUtils.getBean(Dao.class);
            String sqlstr = "select uid from t_role where level >=70";
            Sql sql = Sqls.create(sqlstr);
            sql.setCallback(new SqlCallback() {
                @Override
                public Object invoke(Connection connection, ResultSet resultSet, Sql sql) throws SQLException {
                    ArrayList<Long> arrayList = new ArrayList();
                    while (resultSet.next()) {
                        Long uid = resultSet.getLong("uid");
                        arrayList.add(uid);
                    }
                    return arrayList;
                }
            });
            dao.execute(sql);
            List<Long> list = sql.getList(Long.class);
            PlayerService playerService = SpringUtils.getPlayerService();
            for (Long integer : list) {
                Role aaaaaa = playerService.getPlayerBy(integer);
                if (aaaaaa == null) {
                    continue;
                }
                Mail mail = mailService.createMail(strings[1], msg, 1 * TimeUtil.ONE_DAY);
                mailService.sendNewMail(aaaaaa,mail);
            }
            return;
        }
        if (reqModifyNotice.getNotice().startsWith("onemail==")){
            // onemail==皇甫届默00==标题==邮件内容
            String[] strings = reqModifyNotice.getNotice().split("==");
            String name = strings[1];
            String title = strings[2];
            String mailContent = strings[3];
            long toUid = SpringUtils.getPlayerService().getUidBy(name);
            Role toRole = SpringUtils.getPlayerService().getPlayerBy(toUid);
            MailService mailService = SpringUtils.getMailService();
            Mail mail = mailService.createMail(title, mailContent, 1 * TimeUtil.ONE_DAY);
            mailService.sendNewMail(toRole,mail);
            return;
        }
        partyService.modifyNotice(role,reqModifyNotice.getNotice());
    }

    @RequestMapping
    public void rejectByLevel(IoSession session, ReqPartyRejectLevel reqPartyRejectLevel) {
        Role role = SessionUtils.getRoleBySession(session);
        partyService.setAutoAgreeSetting(role, reqPartyRejectLevel.getMinLevel(), reqPartyRejectLevel.getMaxLevel(), reqPartyRejectLevel.getIsWork(), reqPartyRejectLevel.getIsChange(), reqPartyRejectLevel.getMindao());
    }

    @EventHandler(EventType.LOGIN)
    public void handleLoginEvent(LoginEvent loginEvent) {
       // partyService.handleLogin(loginEvent.getRole());
    }

    @EventHandler(EventType.LOGOUT)
    public void handleLogoutEvent(LogoutEvent logoutEvent) {
        partyService.handleLogout(logoutEvent.getRole());
    }

    @EventHandler(EventType.ROLE_NAME_CHANGE)
    public void handleRoleNameChangeEvent(RoleNameChangeEvent roleNameChangeEvent) {
        partyService.handleRoleNameChange(roleNameChangeEvent.getRole(), roleNameChangeEvent.getPrevName(), roleNameChangeEvent.getCurrName());
    }

    @RequestMapping
    public void controlPartyChannel(IoSession session, ReqControlPartyChannel reqControlPartyChannel) {
        Role role = SessionUtils.getRoleBySession(session);
        long uid = Long.parseLong(reqControlPartyChannel.getGid());
        if (reqControlPartyChannel.getType() == 1) {
            /**禁言*/
            partyService.prohibitSpeaking(role, uid, reqControlPartyChannel.getName(), reqControlPartyChannel.getHours());
        } else if (reqControlPartyChannel.getType() == 2){
            /**解除禁言*/
            partyService.cancelProhibitSpeaking(role, uid, reqControlPartyChannel.getName());
        }
    }

    @RequestMapping
    public void getLog(IoSession session, ReqPartyLog reqPartyLog) {
        Role role = SessionUtils.getRoleBySession(session);
        partyService.getPartyLog(role, reqPartyLog.getStart(), reqPartyLog.getLimit());
    }


    /**
     * 修改帮派名字
     */
    @RequestMapping
    public void rename(IoSession session, ReqPartyRename reqPartyRename) {
        Role role = SessionUtils.getRoleBySession(session);
        partyService.rename(role, reqPartyRename.getName(), reqPartyRename.getType());
    }

    /**
     * 修改帮派Icon
     */
    @RequestMapping
    public void modifyPartyIcon(IoSession session, ReqModifyPartyIcon reqModifyPartyIcon) {
        Role role = SessionUtils.getRoleBySession(session);
        partyService.modifyPartyIcon(role, reqModifyPartyIcon.getOper_type(), reqModifyPartyIcon.getMd5_value(), reqModifyPartyIcon.getFile_data());
    }

    /**
     * 发送帮派公告邮件
     */
    @RequestMapping
    public void sendPartyMail(IoSession session, ReqSendPartyMail reqSendPartyMail){
        Role role = SessionUtils.getRoleBySession(session);
        partyService.sendPartyMail(role,reqSendPartyMail.getTitle(), reqSendPartyMail.getMailMsg());
    }

    /**
     * 研发技能
     */
    @RequestMapping
    public void developSkill(IoSession session, ReqDevelopSkill reqDevelopSkill) {
        Role role = SessionUtils.getRoleBySession(session);
        if (reqDevelopSkill.getPoint() < 0) {
            /**批量研发*/
            short upLevel = (short) Math.abs(reqDevelopSkill.getPoint());
            if (upLevel < Const.MAX_PARTY_SKILL_LEVEL) {
                partyService.developSkill(role, reqDevelopSkill.getSkillNo(), upLevel, 0);
            }
        } else {
            partyService.developSkill(role, reqDevelopSkill.getSkillNo(), 0, reqDevelopSkill.getPoint());
        }
    }

    /**
     * 请求帮派红包配置信息
     * @param session
     * @param reqPartyRedBagSendInfo
     */
    @RequestMapping
    public void reqSendBagInfo(IoSession session, ReqPartyRedBagSendInfo reqPartyRedBagSendInfo) {
        Role role = SessionUtils.getRoleBySession(session);
        partyRedBagHandler.sendRedBagSetting(role);
    }

    /**
     * 请求发送帮派红包
     * @param session
     * @param reqPartySendRedBag
     */
    @RequestMapping
    public void reqSendRedBag(IoSession session, ReqPartySendRedBag reqPartySendRedBag) {
        Role role = SessionUtils.getRoleBySession(session);
        partyRedBagHandler.sendRedBag(role, reqPartySendRedBag.getMoney(), reqPartySendRedBag.getNum(), reqPartySendRedBag.getMsg(), reqPartySendRedBag.getFormat());
    }

    /**
     * 请求帮派红包列表
     * @param session
     * @param reqPartyRedBagList
     */
    @RequestMapping
    public void reqRedBagList(IoSession session, ReqPartyRedBagList reqPartyRedBagList) {
        Role role = SessionUtils.getRoleBySession(session);
        partyRedBagHandler.showRedBagList(role);
    }

    /**
     * 请求显示对应红包
     * @param session
     * @param reqShowRedBag
     */
    @RequestMapping
    public void reqShowRedBag(IoSession session, ReqShowRedBag reqShowRedBag) {
        Role role = SessionUtils.getRoleBySession(session);
        partyRedBagHandler.showRedBag(role, Long.parseLong(reqShowRedBag.getRedBagGid()));
    }

    /**
     * 请求领取对应红包
     * @param session
     * @param reqPartyRecvRedBag
     */
    @RequestMapping
    public void reqRecvRedBag(IoSession session, ReqPartyRecvRedBag reqPartyRecvRedBag) {
        Role role = SessionUtils.getRoleBySession(session);
        partyRedBagHandler.fetchRedBag(role, Long.parseLong(reqPartyRecvRedBag.getRedBagGid()));
    }

    /**
     * 请求显示红包记录
     * @param session
     * @param reqPartyRedBagRecord
     */
    @RequestMapping
    public void reqRedBagRecord(IoSession session, ReqPartyRedBagRecord reqPartyRedBagRecord) {
        Role role = SessionUtils.getRoleBySession(session);
        partyRedBagHandler.showRedBagRecord(role, reqPartyRedBagRecord.getType());
    }

}
